package com.sodaopen.study.utils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.sodaopen.study.entity.AjaxResult;

public class UploadHelper {
	
	private static final Logger log = LoggerFactory.getLogger(UploadHelper.class);
	
	public static AjaxResult saveFile(MultipartFile file, String dir, String uploadPath) {
		return saveFile(file, dir, uploadPath, false);
	}

	public static AjaxResult saveFile(MultipartFile file, String dir, String uploadPath, boolean hideSuffix) {
    	AjaxResult result = new AjaxResult();
        try {
            if (file.isEmpty()) {
            	result.setSuccess(false);
            	result.setData("文件为空");
                return result;
            }
            // 获取文件名
            String fileName = file.getOriginalFilename();
            log.debug("上传的文件名为：" + fileName);
            
            // 设置文件存储路径
            String newName = UUID.randomUUID().toString();
            if(!hideSuffix) {
            	// 获取文件的后缀名
            	String suffixName = fileName.substring(fileName.lastIndexOf("."));
                log.debug("文件的后缀名为：" + suffixName);
            	newName += suffixName;
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
            String mediaPath = "/" + dir + "/" + sdf.format(new Date()) + "/" + newName;
            String path = uploadPath + mediaPath ;
            log.debug("文件的存储的名称为：" + newName);
            File dest = new File(path);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();// 新建文件夹
            }
            file.transferTo(dest);// 文件写入
            
            result.setSuccess(true);
        	result.setData(mediaPath);
            return result;
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        result.setSuccess(false);
    	result.setData("上传失败");
    	return result;
    }
}
